/**
 * Created by Administrator on 2017/6/8 0008.
 */

//import {runSqlInfo} from '../common/dataAccess';
var db = require('../common/dataAccess');
var fs = require('fs');
var moment = require('moment');
var sms = require("../common/sms");

var conf = require("../config/config");

/**
 * 获取当前时间
 * @param parame
 * @param req
 * @param cb
 */
var getTime = function (parame,req,cb) {
    var nowWeek  = new Date().getDay();
    console.log("nowWeek",nowWeek)
    var obj ={};
    obj.commands = "select * from bustime where  status = 1 and  time > '" + nowWeek  + "' order by time asc limit 1;";
    obj.commands +="select * from bustime where status = 1 and time <= '" + nowWeek  + "' order by time asc limit 1;";


    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);

        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            if(info[0].length > 0){
                var differDay = info[0][0].time - nowWeek;
                console.log("differDay is",differDay);
                cb({code:200,info:{data:moment().add(differDay,'days').unix()} /*moment().format('YYYY-MM-DD')*/});
            }else if(info[1].length > 0){
                var differDay = info[1][0].time + 7 - nowWeek;
                console.log("differDay is",differDay);

                cb({code:200,info:{data:moment().add(differDay,'days').unix()} /*moment().format('YYYY-MM-DD')*/});
            }else {
                cb({code:200,info:{data:moment().unix()}})
            }

        }

    })

};

/**
 * 获取帐号信息
 * @param parame
 * @param req
 * @param cb
 */
var getAccountInfo = function (parame,req,cb) {
    console.log("获取帐号信息",parame);
    var  phone = parame.phone;
    if(!phone){
        return cb({code:500,info:"缺少必要参数"});
    }
    var obj = {};
    obj.commands = "select * from taccount_app where phone = '" + phone  + "'";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else
            cb({code:200,info:info[0]});
    })
}

/**
 * 获取班次信息
 * @param parame
 * @param req
 * @param cb
 */
var getBusInfo = function (parame,req,cb) {
    console.log("获取帐号信息",parame);
    var  time = parame.time;
    if(!time){
        return cb({code:500,info:"缺少必要参数"});
    }
    var timeType = new Date(time).getDay();
    console.log("timeType is",timeType);

    var obj = {};
    obj.commands = "select * from bustime where status = 1 and time = '" + time + "';";
    obj.commands += "select * from bustime where status = 1 and time = '" + timeType + "'";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            var value ;
            var times = [];

            if(0 != info[0].length){
                for(var i in info[0]){
                    var temp = {};
                    temp.time = info[0][i].bustype;

                    info[0][i].address = info[0][i].address.replace(/，/g, ",")
                    temp.address  = info[0][i].address.split(",");
                    times.push(temp)
                }
                cb({code:200,info:times});
            }
            else{
                for(var i in info[1]){
                    var temp = {};
                    temp.time = info[1][i].bustype;
                    info[1][i].address = info[1][i].address.replace(/，/g, ",")
                    temp.address  = info[1][i].address.split(",");
                    times.push(temp)
                }
                cb({code:200,info:times});
            }
        }
    })
};

/**
 * 预约班车
 * @param parame
 * @param req
 * @param cb
 */
var orderBus = function (parame,req,cb) {
    var  time = parame.time;
    var  orderTime = parame.orderTime;
    var  phone = parame.phone;
    var  address = parame.address;

    var  num = 1 ;
    if(!phone || !orderTime || !time){
        return cb({code:500,info:"缺少必要参数"});
    };

    if(parame.num){
        num = parame.num;
    }
    var obj = {};
    obj.commands = "replace  into ordertime (time,orderTime,num,address,phone) values("
    + "'" + time + "'"
    + ",'" + orderTime + "'"
    + ",'" + num + "'"
    + ",'" + address + "'"
    + ",'" + phone + "');";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err){
            return cb({code:500,info:"获取信息错误"});
        }
        else{
            if(info.affectedRows >= 1)
                return  cb({code:200,info:{id:info.insertId}});
            else
                return  cb({code:500,info:'预约失败'});
        }

    })
}

/**
 * 获取预约的班车
 * @param parame
 * @param req
 * @param cb
 * @returns {*}
 */
var getOrderBus = function (parame,req,cb) {
    var  time = parame.time;
    var  phone = parame.phone;
    if(!phone  || !time){
        return cb({code:500,info:"缺少必要参数"});
    };

    var obj = {};
    obj.commands = "select * from  ordertime where phone = '" + phone + "' and time ='" + time+ "';";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else
            cb({code:200,info:info[0]});
    })
}

/**
 * 取消班车
 * @param parame
 * @param req
 * @param cb
 */
var cancleBus = function (parame,req,cb) {
    var   id = parame.id;

    if(!id ){
        return cb({code:500,info:"缺少必要参数"});
    };

    var obj = {};
    obj.commands = "update   ordertime  set status = 1 where id = '" + id  + "';";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            if(info.affectedRows >= 1)
                return  cb({code:200,info:'取消成功'});
            else
                return  cb({code:500,info:'取消失败id错误'});
        }

    })
}

/**
 * 获取短信验证码
 * @param parame
 * @param req
 * @param cb
 */
var getVerification = function (parame,req,cb) {
    var  phone = parame.phone;
    if(!phone){
        return cb({code:500,info:"缺少必要参数"});
    };
  
    phone = JSON.parse(phone);
    
  var obj = {};
	  obj.commands = " SELECT count(*) total FROM taccount  t1 left JOIN trelation t2 on t1.id = t2.id "
	  + " WHERE t1.phone = '" + phone + "'"
	  + " or t2.phone = '" + phone + "'"
	  + " UNION "
	  + " SELECT count(*) total FROM taccount  t1 right JOIN trelation t2 on t1.id = t2.id "
	  + " WHERE t1.phone  = '" + phone + "'"
	  + " or t2.phone  = '" + phone + "'";
  
  db.runSqlInfo(obj,function(phoneInfo,err){
    if(err)
      return cb({code:500,info:"验证码发送失败"});
    else{
        if(phoneInfo[0].total <= 0){
          return cb({code:500,info:"非本院人员，亲属无法注册"});
        }
      
      var code = getrandomNumber (6);
      var msgInfo = JSON.stringify({code:code});
      
      sms.sendMessage(phone, 'SMS_100825003',  msgInfo, function (err,info) {
        console.log("短信发送日志",err,info);
        if(err)
          return cb({code:500,info:'验证码发送失败'})
        else {
          var obj ={};
          obj.commands = "replace  into verification (phone,code) values("
            + "'" + phone + "'"
            + ",'" + code + "')";
      
          db.runSqlInfo(obj,function(info,err){
            if(err)
              return cb({code:500,info:"验证码发送失败"});
            else{
              if(info.affectedRows >= 1){
                //deleteVerification({phone:phone})
                return  cb({code:200,info:'验证码发送成功'});
              }
              else
                return  cb({code:500,info:'验证码发送失败 '});
          
            }
          });
      
          return  cb({code:200,info:code});
        }
    
      });
    }
  });
}

/**
 * 生成数字验证码
 * @param num
 * @returns {string}
 */
var getrandomNumber = function (num) {
    var code="";
    for (var i = 0 ;i<num ;i++){
        code += Math.floor(Math.random()*10);
    }
    return code;
}
/**
 * 10分钟后删除验证码
 * @param info
 */
var deleteVerification = function (info) {
    console.log("10分钟后删除验证码");
    var phone = info.phone;
    setTimeout(function () {
        var obj = {};
        obj.commands = "delete from verification where phone = '" + phone + "'";
        db.runSqlInfo(obj,function(info,err){
            if(err){
                console.error(err);
            } else{
                console.log(info);
            }
        });
    },1000 * 60 * 10)
}
/**
 * 注册
 * @param parame
 * @param req
 * @param cb
 */
var register = function (parame,req,cb) {
    console.log(parame);
    var  phone = parame.phone;
    var  code = parame.code;
    var  password = parame.password;
    if(!phone || !code ||!password){
        return cb({code:500,info:"缺少必要参数"});
    };

    var obj ={};
    obj.commands = "select count(*) total from taccount_app where phone = "
    + "'" + phone + "';";

    obj.commands += "select count(*) total from verification where phone = "
    + "'" + phone + "'"
    + "  and code = "
    + "'" + code + "'";

    db.runSqlInfo(obj,function(info,err){
        console.log(info)
        if(err)
            return cb({code:500,info:"注册失败数据库查询错误"});
        else{
            if(info[0][0].total < 1){
                if(info[1][0].total < 1){
                    return  cb({code:500,info:'注册失败 ,验证码错误'});
                }
                obj.commands = "insert into taccount_app(phone,password) values("
                + "'" + phone + "',"
                + "'" + password + "');";

                db.runSqlInfo(obj,function(info,err){
                    if(err)
                        return cb({code:500,info:"注册失败数据库查询错误"});
                    else{
                        if(info.affectedRows >= 1){
                            return  cb({code:200,info:'注册成功'});
                        }
                        else
                            return  cb({code:500,info:'注册失败 '});
                    }
                });
            }
            else{
                return  cb({code:500,info:'注册失败 ,用户已经存在'});
            }

        }
    });
};

/**
 * 登入
 * @param parame
 * @param req
 * @param cb
 */
var doLogin =function (parame,req,cb) {
    var  phone = parame.phone;
    var  password = parame.password;

    if(!phone || ! password){
        return cb({code:500,info:"缺少必要参数"});
    };

    var obj = {};
    obj.commands = "select * from taccount_app where phone = '"
        + phone + "'"
    + " and password = '" + password + "';";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            if(!info[0] || info.length <= 0){
                return  cb({code:500,info:"没有该帐号信息"});
            }
            return  cb({code:200,info:info[0]});
        }
    })
}



/**
 * 获取重阳新生信息
 * @param parame
 * @param req
 * @param cb
 */
var getNewBorn =function (parame,req,cb) {
    var  time = parame.time;

    var obj = {};

    obj.commands = "select * from newborn";
    if(time)
        obj.commands += " where time >= '" + time + "'";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            var resValue = {};
            resValue.code = 200;
            resValue.info= [];
            for(var i in info){

                info[i].detailContent = info[i].detailContent.replace(/<p>/g,'');
                info[i].detailContent = info[i].detailContent.replace(/<\/p>/g,'');
                info[i].detailContent = info[i].detailContent.replace(/alt=""/g,'');
                var tempInfo = {};
                tempInfo.title = info[i].title;
                tempInfo.msg = info[i].msg;
                tempInfo.time = moment(info[i].time).format("YYYY-MM-DD") ;
                tempInfo.type = info[i].type;
                tempInfo.info = {
                    title:info[i].detailTitle,
                    content:info[i].detailContent,

                };
               /* if(info[i].image){
                    tempInfo.info.image= conf.url + info[i].image
                }*/
                resValue.info.push(tempInfo);
            }
            return  cb(resValue);
        }
    })
}

/**
 * 获取重阳故事信息
 * @param parame
 * @param req
 * @param cb
 */
var getStory =function (parame,req,cb) {
    var  time = parame.time;
    var obj = {};
    obj.commands = "select * from story";
    if(time)
        obj.commands += " where time >= '" + time + "'";

    db.runSqlInfo(obj,function(info,err){
        console.log("info is:",info);
        if(err)
            return cb({code:500,info:"获取信息错误"});
        else{
            var resValue = {};
            resValue.code = 200;
            resValue.info= [];
            for(var i in info){
                info[i].detailContent = info[i].detailContent.replace(/<p>/g,'');
                info[i].detailContent = info[i].detailContent.replace(/<\/p>/g,'');
                info[i].detailContent = info[i].detailContent.replace(/alt=""/g,'');

                var tempInfo = {};
                tempInfo.title = info[i].title;
                tempInfo.msg = info[i].msg;
                tempInfo.time = moment(info[i].time).format("YYYY-MM-DD") ;
                tempInfo.type =  info[i].type;
                tempInfo.info = {
                    title:info[i].detailTitle,
                    content:info[i].detailContent,
                };
              /*  if(info[i].image){
                    tempInfo.info.image= conf.url + info[i].image
                }*/

                resValue.info.push(tempInfo);
            }
            return  cb(resValue);
        }
    })
}


exports.getVerification = getVerification;
exports.register = register;
exports.doLogin = doLogin;
exports.getTime = getTime;

exports.getAccountInfo = getAccountInfo;
exports.cancleBus = cancleBus;
exports.orderBus = orderBus;
exports.getBusInfo = getBusInfo;
exports.getOrderBus = getOrderBus;
exports.getNewBorn = getNewBorn;
exports.getStory = getStory;